﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using publicLibrary;
using System.Dynamic;

using MongoDB.Driver.Builders;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization;

namespace asMeishi.web.Controllers
{
    
    using Models;
    using Classes;

    public class shopController : Controller
    {
        //
        // GET: /shop/
        [authorityFilter(actionEnum.manage,actionTypeEnum.str)]
        public ActionResult Index()
        {
            //验证
            if (userC.loginUser.group == "100") { 
            }

            shopC shopC = new shopC();
            ViewData.Model = shopC.getAll().ToList();

            return View();
        }
        /// <summary>
        /// 得到数据库映射字段
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        [NonAction]
        private string getMongoMapField(string str ){
            return BsonClassMap.LookupClassMap(typeof(shop)).GetMemberMap(str).ElementName;
        }
        //*******************有问题lys**********************
        public ActionResult search(string keyword,string resultType,int pageIndex = 0, int pageSize = 10)
        {

            //模糊查询
            //keyword加入库中               
            if (!string.IsNullOrWhiteSpace(keyword))

            {
                var sc = new shopC();

                /*********有问题lys，如何解决页面刷新时keyword并不是新输入的词，却不存数据库?********/
                keyWordC kwc = new keyWordC();
                kwc.add(keyword);


                string regxStr = "" + keyword.Replace(" ","|").Replace("　","|").Replace(",","|").Replace("，","|") + "";
                System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(regxStr, System.Text.RegularExpressions.RegexOptions.Compiled);



                List<IMongoQuery> imqs = new List<IMongoQuery>();
                imqs.Add(Query.EQ(getMongoMapField("name"), regx));
                //imqs.Add(Query.EQ(getMongoMapField("nameCN"), regx));
                imqs.Add(Query.EQ(getMongoMapField("intro"), regx));
                imqs.Add(Query.EQ(getMongoMapField("foodStyle"), regx));
                imqs.Add(Query.EQ(getMongoMapField("addressStr"), regx));

                imqs.Add(Query.EQ(getMongoMapField("food"), regx));
                
                var _shops = sc.sift(Query.Or(imqs)).Skip(pageSize*pageIndex).Take(pageSize);
                int _count = _shops.Count();
                var __shops = _shops.Skip(pageIndex * pageSize).Take(pageSize);
                /***********有问题lys 以下这样模糊查询不知道性能怎么样**********
                _shops = _shops.Where(d => (d.name != null && d.name.Contains(keyword))
                    || (d.nameCN != null && d.nameCN.Contains(keyword))
                    || (d.intro != null && d.intro.Contains(keyword))
                    || (d.addressStr != null && d.addressStr.Contains(keyword))
                    || (d.foodStyleList != null && d.foodStyle.Contains(keyword))
                    || (d.foodOtherClass != null && d.foodOtherClass.Contains(keyword))
                    || (d.food != null && d.food.Contains(keyword)));
                 * */
                ViewBag.sum = _count;
                if (resultType == "ajaxHTML")
                {
                    ViewBag.more = (pageIndex + 1) * pageSize < ViewBag.sum ? true : false;
                    return View("siftResult", __shops);
                }
                else {
                    return View("shopSift", __shops);
                }
            }

            return RedirectToAction("shopSift");

        }
        /// <summary>
        /// 店筛选 附条件
        /// </summary>
        /// <returns></returns>
        public ActionResult shopSift(string parameter,string resultType,int pageIndex=0,int pageSize=10)
        {
            IEnumerable<shop> _shops;
            long _count;
            shopC sc = new shopC();
            //如果parameter,keyword都无参数，返回空
            if(string.IsNullOrWhiteSpace(parameter)){
                _shops = new List<shop>();
                //_count = sc.sum();
                _count = 0;
            }
            //如果parameter 为all 返回所有记录
            else if (parameter == "all") {
                _shops = new List<shop>();
                //_shops = sc.getAll();
                //_count = _shops.Count();
                _count = publicDictApp.shopTotalCount;
            }else{
                //如果只有parameter为空，返回全部提供为keyword检索用
                //if(string.IsNullOrWhiteSpace(parameter)){
                //    _shops = sc.getAll().Where(d => d.releaseStep != 5 && d.able == true);

                //}
                ////如果parameter有值．返回对应结果
                //else{

                var __shops = sc.sift(transformSiftToQ(parameter));
                _count = __shops.Count();
                _shops = __shops.Skip(pageIndex * pageSize).Take(pageSize);
                //}

                
            }
            //判断请求类型
            if (resultType == "ajaxHTML")
            {
                ViewBag.more = (pageIndex + 1) * pageSize < _count ? true : false;
                return View("siftResult", _shops);
            }
            else
            {
                ViewData.Model = _shops.ToList();
                ViewBag.sum = _count;

                return View();
            }
        }
        public ActionResult reSum(string parameter)
        {
            //parameter = "classMain:(02|12),classOther:(05|13)";


            shopC shopC = new shopC();
            var _c = Content(shopC.sum(transformSiftToQ(parameter)).ToString());

            return _c;
        }

        [NonAction]
        private IMongoQuery transformSiftToQ(string parameter)
        {
            //BsonClassMap.RegisterClassMap<shop>();


            //如parameter为空　返回全部
            if (string.IsNullOrWhiteSpace(parameter))
            {
                return null;
            }

            List<QueryDocument> q = new List<QueryDocument>();

            foreach (var item in parameter.Split(','))
            {
                if (item != "")
                {
                    string[] itemArr = item.Split(':');
                    string BsonElementField = BsonClassMap.LookupClassMap(typeof(shop)).GetMemberMap(itemArr[0]).ElementName;

                    //是list字段
                    if ((new String[] { "foodStyleList", "foodStyle" }).Contains(itemArr[0]))
                    {
                        
                        List<BsonValue> lbv = new List<BsonValue>();
                        BsonElement be = new BsonElement("$in", new BsonArray(itemArr[1].Split('|')));
                        QueryDocument bee = new QueryDocument(be);
                        QueryDocument xq = Query.Or(Query.ElemMatch(BsonElementField, bee)) as QueryDocument;
                        q.Add(xq);

                        //{foodStyle:{$elemMatch:{$in:[01]}}}   01出错没有引号
                        //BsonDocument xq = QueryDocument.Parse("{"+itemArr[0]+":{$elemMatch:{$in:["+itemArr[1].Replace('|',',')+"]}}}");
                        //QueryDocument qq = new QueryDocument(xq);

                    }
                    //范围，消费
                    else if ("cost" == itemArr[0]) {

                        List<QueryDocument> lq = new List<QueryDocument>();
                        foreach (var values in itemArr[1].Split('|'))
                        {
                            string[] mm = values.Split('-');

                            int min;
                            int max;
                            BsonDocument xq;

                            min = int.Parse(mm[0]);

                            if (mm[1] == "∞")
                            {

                                xq = QueryDocument.Parse("{" + BsonElementField + ":{$lte:" + min + "}}");
                            }
                            else
                            {
                                max = int.Parse(mm[1]);
                                xq = QueryDocument.Parse("{" + BsonElementField + ":{$gte:" + min + ",$lte:" + max + "}}");
                            }
                            lq.Add(new QueryDocument(xq));

                        }

                        q.Add(Query.Or(lq) as QueryDocument);
                    }
                    else{

                        List<QueryDocument> lq = new List<QueryDocument>();

                        foreach (var values in itemArr[1].Split('|')) {

                            lq.Add(Query.EQ(BsonElementField, values) as QueryDocument);
                        };
                    
                        QueryDocument xq = Query.Or(lq) as QueryDocument;
                        q.Add(xq);
                    }
                }
                
            }
            //增加 发布和可用性过滤
            q.Add(Query.EQ("RL", 5) as QueryDocument);
            q.Add(Query.EQ("able", true) as QueryDocument);
            return Query.And(q);
            
        }
        /// <summary>
        /// 建立店，根据Id，如果该店处于发布前期则跳转到---------店Create页面
        /// 适用于用户建立店未正式发布的补全功能
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ActionResult Release(string shopId)
        {
            return RedirectToAction("Create");
        }
        /// <summary>
        /// 建立店，分为1,2,3,4,5,步，如果该店处于发布前期状态(releaseStep不为0)，则跳转到相应的填写页面
        /// </summary>
        /// <param name="shopId"></param>
        /// <param name="fc"></param>
        /// <param name="nextStep"></param>
        /// <returns></returns>
        [authorityFilter(actionEnum.createShop)]
        public ActionResult Create(string shopId, FormCollection fc)
        {
            Boolean directAction = true;
            var _name=fc["name"];
            var _nextStep = fc["nextStep"];
            if (!string.IsNullOrWhiteSpace(fc["directAction"])) { directAction = false; }

            int nextStep = 0;
            shopC sc = new shopC();
            shop s = sc.getById(shopId);



            if (s == null)
            {

                if (!string.IsNullOrWhiteSpace(_name))
                {
                    s = sc.getByName(_name);
                    if (s != null)
                    {
                        if (s.releaseStep == 5)
                        {

                            ModelState.AddModelError("create", "该已经发布");
                            ViewData.Model = new shop() { name = _name };
                            return View();

                        }
                    }
                }

            }
            //如果还是不存在,新建
            if (s == null) { 
                s = sc.createDefault(userC.loginUser);
            }
            if (_nextStep == null)
            {
                nextStep = 0;
            }
            else {
                nextStep = Convert.ToInt32(_nextStep);
            }


            switch (nextStep)
            {
                case 0:
                    ViewBag.nextStep = 1;
                    return View(s);

                case 1://建立新shop名，并进入下一步电话、介绍、规模等基本信息表单
                    string shopName = _name;
                    string shopNameVallid = fc["shopNameVallid"];
                    if (shopName.isInputValid() && !directAction)
                    {

                        //如果第一次店名提交
                        if (shopNameVallid!="true")
                        {
                            var ss = sc.getLikeName(shopName).Where(d=>d.releaseStep==5);
                            //如果存在值，反回到名称提交确认页面
                            if (ss.Any())
                            {
                                s.name = shopName;
                                ViewBag.someShop = ss;
                                ViewBag.shopName = shopName;
                                ViewBag.nextStep = 1;
                            }
                                //直接提交
                            else {
                                s.name = shopName;
                                ViewBag.nextStep = 2;

                                sc.save(s);                           
                            }
                        }
                        //经确认后第二次提交
                        else
                        {

                            s.name = shopName;
                            ViewBag.nextStep = 2;

                            sc.save(s);
                        }

                    }
                    else {

                        ViewBag.nextStep = 1;
                        
                    }
                    return View(s);

                case 2://地址、电话、介绍等基本信息写入，并进入下一步硬件条件等信息表单
                    //安全问题，以后解决

                    
                    if(!directAction){

                        TryUpdateModel(s, fc);

                        //读取foolstyle
                        string[] foodstyles = fc.GetValues("foodstyle");
                        if (foodstyles != null)
                        {
                            s.foodStyleList = new List<string>();
                            s.foodStyleList.AddRange(foodstyles);
                            sc.onlyEditShopfoodStyle(ref s);
                        }

                        sc.save(s);
                        ViewBag.nextStep = 3;
                    }else{
                        ViewBag.nextStep = 2;
                    }
                    return View(s);

                case 3://硬件条件等信息写入。并进入下一步写点评、推荐菜

                    
                    if(!directAction){
                        TryUpdateModel(s, fc);
                        
                        //读取硬件标签
                        string[] utilityTags = fc.GetValues("utilityTags");
                        if (utilityTags != null)
                        {

                            s.utilityTags = new List<string>();
                            s.utilityTags.AddRange(utilityTags);
                        }

                        sc.save(s);
                        ViewBag.nextStep = 4;
                    }else{
                        ViewBag.nextStep = 3;
                    }
                    return View(s);
                case 4://点评及推荐店中菜信息写入。并进入下一步发布 

                    if(!directAction){

                        List<food> foods = new List<food>();
                        string[] foodNames = fc.GetValues("foodName");
                        string[] foodIntros = fc.GetValues("foodIntro");
                        string[] foodGrades = fc.GetValues("foodGrade");

                        string commentContent = fc["commentContent"];
                        int? cost = fc["cost"].tryToInt();;
                        int? quality = fc["quality"].tryToInt();
                        int? service = fc["service"].tryToInt();
                        int? priceQuality = fc["priceQuality"].tryToInt();
                        //写入shop表
                        shopC shopC = new shopC();
                        sc.updataFoodAndDetial(ref s, foodNames, foodIntros, foodGrades, userC.loginUser, 0);

                        sc.save(s);
                        ViewBag.nextStep = 5;

                        sc.addComment(ref s, commentContent, cost, quality, service, priceQuality,foods,userC.loginUser,0);
                    }
                    else {

                        ViewBag.nextStep = 4;
                    }

                    return View(s);
                case 5://发布
                    if (!directAction)
                    {
                        string aaction = fc["aaction"];
                        if (aaction == "delete")
                        {
                            sc.del(shopId.toOId());
                            ViewBag.resultType = 2;
                            return View("CreateResult", s);
                        }
                        else if (aaction == "reCreate")
                        {ViewBag.resultType = 1;

                            sc.save(s);

                            return RedirectToAction("Create", new { shopId = shopId, fc = new FormCollection(), nextStep = -1 });
                        }
                        else if (aaction == "release") { //发布并转到成功页面
                            s.releaseStep = 5;
                            s.lasttime = DateTime.Now;

                            
                            ViewBag.resultType = 1;

                            //日志
                            historyC<shop>.Add(s.Id, s.name, historyTypeEnum.建立, null, userC.loginUser);

                            commentC cc = new commentC();
                            var c = cc.getByShopId(s.Id);
                            var ci=0;
                            if (c.Any()) {
                                foreach (var _c in c) {
                                    _c.release = 1;//发布
                                    ci++;
                                    cc.save(_c);
                                    //comment日志
                                    historyC<shop>.Add(s.Id, "comment", historyTypeEnum.建立,_c.Id.ToString(), userC.getById(_c.userId));
                                }
                            }
                            s.comment_number = ci;
                            sc.save(s);
                            return View("CreateResult",s);

                        }

                    }
                    else {
                        ViewBag.nextStep = 5;
                    }
                    return View(s);
                default:

                    return View(s);
            }


        }

        public ActionResult CreateAction(string shopId,string aaction="") {
            shopC sc = new shopC();

            if (aaction == "del")
            {
                sc.del(shopId.toOId());
                return View();
            }
            else if (aaction == "reCreate")
            {
                shop s = sc.getById(shopId);
                s.releaseStep = 0;
                sc.save(s);

                return RedirectToAction("Create", new { shopId = shopId,fc=new FormCollection(),nextStep=-1 });
            }
            return View();
        }

        public ActionResult Detail(string id, string channel, string parameter = "") //p1:channel
        {
            shopC shopC = new shopC();
            shop shop = shopC.getById(id);
            if (shop == null) { 
                //throw 
                    new asMeishiException("不存在的食场");
                return Content("??"); 
            }
            ViewData.Model = shop;

            ViewBag.channel = channel ?? "";
            ViewBag.parameter = parameter;

            return View("Detail");
        }

        public ActionResult ViewPic(string id)
        {
            shopC shopC = new shopC();
            ViewData.Model = shopC.getById(id).picUrlList;

            return View();
        }
        public ActionResult ViewComment()
        {
            return View();
        }

        //坐标地点附近查询
        public ActionResult Ajax_nearby(string lnglat, double range)
        {
            IMongoQuery q = null;
            var ll = lnglat.trySplit(",");
            q = Query.Near("ANL", double.Parse(ll[0]), double.Parse(ll[1]), range);

            shopC sc = new shopC();
            var ss = sc.sift(q).Select(d=>new {d.name,d.sum_score,d.score_number,d.street,d.size,d.foodStyle,d.cost});
            return Json(ss, JsonRequestBehavior.AllowGet);

        }
        public ActionResult nearbyShop(string id, double range=1) {
            shopC sc = new shopC();
            shop s = sc.getById(id);
            IMongoQuery q=null;
            if(s.longitudeAndLatitude!=null){
                q = Query.Near("ANL",s.longitudeAndLatitude[0], s.longitudeAndLatitude[1],range);
            }
            /*
            List<BsonValue> bvs = new List<BsonValue>();
            bvs.Add(BsonValue.Create(s.longitudeAndLatitude[0]));
            bvs.Add(BsonValue.Create(s.longitudeAndLatitude[1]));

            Query.All("ANL",bvs);
            
            var n = Query.NE("ANL",);
             */
            if (q == null) {
                ModelState.AddModelError("", "定位坐标前，是查不到相关数据的");
                return View("p_nearbyShop");
            }
            var qq = Query.And(new IMongoQuery[]{Query.EQ("RL", 5),Query.EQ("able",true),q});
            var ss = sc.sift(qq).Skip(1).Take(15);
            ViewBag.source_longitudeAndLatitude = s.longitudeAndLatitude;
            return View("p_nearbyShop",ss);

        }
        /// <summary>
        /// 添加促销内容
        /// </summary>
        /// <param name="id"></param>
        /// <param name="content"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult addSale(string id,string content,string type) {
            if (string.IsNullOrWhiteSpace(content)) { return Content(AjaxCallBackInfo.jsonError("内容不能为空")); }

            shopC sc = new shopC();
            shop shop = sc.getById(id);
            sale sale =sc.addSale(shop, content,type.ToInt()??0, userC.loginUser);

            if (sale == null){
                return Content(AjaxCallBackInfo.jsonError());
            }
            else {
                //日志
                historyC<shop>.Add(shop.Id, "Sale", historyTypeEnum.修改, sale.Id.ToString(), userC.loginUser);
                return Content(AjaxCallBackInfo.jsonOk(sale.Id.ToString()));
            }
            
            
        }
        /// <summary>
        /// 删除一个sale
        /// </summary>
        /// <param name="id"></param>
        /// <param name="saleId"></param>
        /// <returns></returns>
        public ActionResult delSale(string id, string saleId) {
            shopC sc = new shopC();
            shop shop = sc.getById(id);
            sale sale = sc.delSale(shop, saleId);
            //日志
            historyC<shop>.Add(shop.Id, "Sale", historyTypeEnum.删除,sale.content, userC.loginUser);
            return Content(AjaxCallBackInfo.jsonOk(saleId));
        }
        /// <summary>
        /// 设定sale的有效性,string "0"为失效,"1"为有效
        /// </summary>
        /// <param name="id"></param>
        /// <param name="saleId"></param>
        /// <param name="able"></param>
        /// <returns></returns>
        public ActionResult ableSale(string id, string saleId,string able="0") {
            shopC sc = new shopC();
            shop shop = sc.getById(id);
            if (able == "0")
            {
                sc.setAbleSale(shop, saleId, false);

            }
            else if(able=="1") {
                sc.setAbleSale(shop, saleId, true);
                
            }
            historyC<shop>.Add(shop.Id, "Sale", historyTypeEnum.修改状态, saleId, userC.loginUser);
            return Content(AjaxCallBackInfo.jsonOk(saleId));            
        }
        /// <summary>
        /// ajax revise 补修提交 用户开放
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Ajax_revise(string id, string name, string value)
        {
            //用户权限验证验证
            shopC shopC = new shopC();
            shop shop = shopC.getById(id);
            
            switch (name)
            {
                case "shopCity":
                    shop.city = value;
                    break;
                case "shopArea":
                    shop.area = value;
                    break;
                case "shopStreet":
                    shop.street = value;
                    break;
                case "shopName":
                    shop.name = value;
                    break;
                case "shopNameCN":
                    shop.nameCN = value;
                    break;
                case "shopNameEN":
                    shop.nameEN = value;
                    break;
                case "longitudeAndLatitude":

                            //如果转换不对时。值为空
                            try
                            {
                                var v = value.Split(',');
                                var _lng = double.Parse(v[0]);
                                var _lat = double.Parse(v[1]);
                                if (shop.longitudeAndLatitude == null)
                                {
                                    shop.longitudeAndLatitude = new double[] { 0, 0 };
                                }
                                shop.longitudeAndLatitude[0] = _lng;
                                shop.longitudeAndLatitude[1] = _lat; 

                            }
                            catch {
                                shop.longitudeAndLatitude = null;
                            }

                    break;
                case "shopAddressStr":
                    shop.addressStr = value;
                    break;
                case "shopFoodStyle":
                    var vvv = value.Split(new string[] { "," }, StringSplitOptions.None).ToList<string>();
                    shop.foodStyleList = vvv;
                    shopC.onlyEditShopfoodStyle(ref shop);

                    break;
                case "shopClassMore":
                    var vv = value.Split(new string[] { "," }, StringSplitOptions.None).ToList<string>();
                    shop.utilityTags = vv;
                    break;
                case "shopEnvironment":
                    shop.environment = value;
                    break;
                case "shopClassOther":
                    shop.foodOtherClass = value;
                    break;
                case "shopFit":
                    shop.fit = value;
                    break;
                case "shopHead":
                    shop.head = value.ToInt() ?? 0;
                    break;
                case "shopIntro":
                    shop.intro = value;
                    break;
                case "shopItem":
                    var foods = value.Split(new string[] { "},{" }, StringSplitOptions.None).ToList<string>();
                    shop.food = foods;
                    break;
                case "shopSize":
                    shop.size = value.ToInt() ?? 0;
                    break;
                case "telephone":
                    shop.telephone = value;
                    break;
                case "shopTags":
                    shop.tags = value;
                    break;
                case "shopUtilityTags":
                    var utilityTags = value.Split(new string[] { "," }, StringSplitOptions.None).ToList<string>();
                    shop.utilityTags = utilityTags;
                    break;

                case "shopWeb":
                    shop.web = value;
                    break;
                //case "shopPay":
                //    shop.pay =value;
                //    break;
                case "shopAlly":
                    shop.ally = value;
                    break;
                //case "shopMemberAble":
                //    if(value=="true"){shop.member=true;break;};
                //    if(value=="false"){shop.member=false;break;};
                //    if (value == "null") { shop.member = null; break; };
                //    break;
                default:
                    return Content(AjaxCallBackInfo.jsonError());
            }
            shop.lasttime = DateTime.Now;
            shop.lastReviseUser = userC.loginUser.Id;
            shopC.save(shop);

            //用户积分动作
            //userJF.up
            //用户积分动作end

            //用户减权限数
            //用户减权限数

            //日志
            historyC<shop>.Add(shop.Id,name,historyTypeEnum.修改,null,userC.loginUser);
            //日志
            return Content(AjaxCallBackInfo.jsonOk());
        }

        [HttpPost]
        [authorityFilter(actionEnum.upFile)]
        public ActionResult Ajax_addPic()
        {
            shopC shopC = new shopC();
            HttpFileCollectionBase files = Request.Files;
            string shopId = Request.Params.Get("Id");

            shop shop = shopC.getById(shopId);

            if (string.IsNullOrEmpty(shopId) || files.Count == 0) { return Content("error"); }
            string fileName = shopC.addPic(ref shop, files[0]);

            //增加历史记录
            if (fileName != null)
            {
                shopC.save(shop);
                historyC<shop>.Add(shopId.toOId(), "图片", historyTypeEnum.添加, fileName, userC.loginUser);
            }

            //返回
            return Content(AjaxCallBackInfo.jsonOk());

        }
        [HttpPost]
        [OutputCache(Duration=0)]
        //[ValidateInput(false)]
        public ActionResult Ajax_delPic(string Id, string picUrl)
        {
            shopC sc = new shopC();
            shop s = sc.getById(Id);
            var x = sc.delPic(ref s, picUrl);
            if (x)
            {
                sc.save(s);
                historyC<shop>.Add(s.Id, "图片", historyTypeEnum.删除, picUrl, userC.loginUser);
                return Content(AjaxCallBackInfo.jsonOk());
            }
            else { 
                return Content(AjaxCallBackInfo.jsonError("删除图片出错"));
            }


        }
        /// <summary>
        /// 增加food
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Ajax_updataFood(string id,FormCollection fc)
        {

            string shopId = id;
            string foodsStr = fc["foodsStr"];


            //写入shop表
            shopC sc = new shopC();
            shop shop = sc.getById(shopId);
            sc.updataFood(ref shop, foodsStr, userC.loginUser);

            return Content(AjaxCallBackInfo.jsonOk());
        }
        /// <summary>
        /// add评价和推荐菜
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="fc"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult addCommentAndFood(string Id, FormCollection fc)
        {
            shopC sc = new shopC();
            shop s = sc.getById(Id);
            IEnumerable<food> foods=null;
            string[] foodNames = fc.GetValues("foodName");

            string[] foodIntros = fc.GetValues("foodIntro");
            string[] foodPrices = fc.GetValues("foodPrice");

            string commentContent = fc["commentContent"];
            int? cost = fc["cost"].tryToInt(); ;
            int? quality = fc["quality"].tryToInt();
            int? service = fc["service"].tryToInt();
            int? priceQuality = fc["priceQuality"].tryToInt();
            //写入shop表

            try
            {
                /*
                List<string> _foodNames = new List<string>();
                List<string> _foodImpresses = new List<string>();
                
                //去除无效的food
                for(int i=0;i<foodNames.Length;i++){
                    foodNames[i] = foodNames[i].Trim();
                    if(!string.IsNullOrWhiteSpace(foodNames[i])){
                        _foodNames.Add(foodNames[i]);
                        _foodImpresses.Add(foodImpresses[i]);
                        

                    }
                }
                */
                //foods的历史记录放在foods.cs中
                foods = sc.updataFoodAndDetial(ref s, foodNames, foodIntros, foodPrices, userC.loginUser, 0);

                comment c = sc.addComment(ref s, commentContent, cost, quality, service, priceQuality, foods,userC.loginUser, 0);
                sc.save(s);

                historyC<shop>.Add(s.Id, "comment", historyTypeEnum.添加, c.Id.ToString(), userC.loginUser);
                
            }
            catch (Exception e){
                new asMeishiException("出错");
            }

            return RedirectToAction("Detail", new { id = s.Id, channel = "comments" });
  
        
        }
        [HttpPost]
        public ActionResult addFoodAndImpress(string Id, FormCollection fc) {
            shopC sc = new shopC();
            shop s = sc.getById(Id);
            IEnumerable<food> foods = null;
            string[] foodNames = fc.GetValues("foodName");
            string[] foodIntros = fc.GetValues("foodIntro");
            string[] foodPrices = fc.GetValues("foodPrice");
            try
            {
                List<string> _foodNames = new List<string>();
                List<string> _foodImpresses = new List<string>();
                //去除无效的food
                /*
                for (int i = 0; i < foodNames.Length; i++)
                {
                    foodNames[i] = foodNames[i].Trim();
                    if (!string.IsNullOrWhiteSpace(foodNames[i]))
                    {
                        _foodNames.Add(foodNames[i]);
                        _foodImpresses.Add(foodImpresses[i]);


                    }
                }
                 */
                foods = sc.updataFoodAndDetial(ref s, foodNames,foodIntros,foodPrices, userC.loginUser, 0);
                sc.save(s);
            }
            catch (Exception e)
            {
                new asMeishiException("出错");
            }
                //foods的历史记录放在foods.cs中

            return RedirectToAction("Detail", new { id = s.Id, channel = "foods" });
        }

        public ActionResult resetStatistics(string id) {
            shopC sc = new shopC();
            var s = sc.getById(id);
            sc.statistics(ref s, null, true);
            sc.save(s);
            return Content("ok");
        }
        [authorityFilter(actionEnum.delImpression)]
        public ActionResult delimpression(string shopId, string content)
        {
            //shop shop = shopC.getById(shopId);
            impressionC<shop> mcc = new impressionC<shop>();
            mcc.delByShopIdByContent(shopId.toOId(), content).ToString();

            /***********历史************/
            return Content(AjaxCallBackInfo.jsonOk());
            
        }

        public ActionResult addimpression(string shopId, string content, int type)
        {
            impressionC<shop> mcc = new impressionC<shop>();
            var data = mcc.create(shopId.toOId(),userC.loginUser);
            data.content = content;
            data.targetId = shopId.toOId();
            mcc.add(data);

            /***********历史************/
            return Content(AjaxCallBackInfo.jsonOk());
        }

        public ActionResult getImpressions(string id, int? p1)
        {
            int pageNum = p1 ?? 1;
            impressionC<shop> ic = new impressionC<shop>();
            var data = ic.getByTargetId(id.toOId()).OrderByDescending(d => d.datetime);

            paging<impression> paging = new paging<impression>(data, 20);
            ViewData.Model = paging.content(pageNum).ToList();
            ViewBag.pageInfo = paging.info();


            return View("p_impressions");
        }
        public ActionResult getComments(string id, int? p1,string pSize="10")
        {
            int pageNum = p1 ?? 1;
            //效率低
            int pageSize = Convert.ToInt32(pSize);

            commentC cc = new commentC();
            var data = cc.getByShopId(id.toOId()).OrderByDescending(d => d.datetime);
            var userDb = userC.getDB();

            IEnumerable<user> users = userDb.query;

            paging<comment> paging = new paging<comment>(data, pageSize);
            var _data = paging.content(pageNum);
            ViewBag.pageInfo = paging.info();
            ViewBag.shopId = id;

            //多表联查
            var result = (from c in _data //第一个表
                         join u in users //第二个表
                         on c.userId equals u.Id //条件
                         into uDef //默认值处理
                         from uD in uDef.DefaultIfEmpty(userC.guestUser)
                         select new Object[] { c, uD }).ToList(); //返回
            


            return View("p_comments", result);
        }

        public ActionResult getFoodsMenu(string id)
        {

            foodC itc = new foodC();
            var data = itc.getsByShopId(id.toOId()).OrderByDescending(d => d.lastDatatime);
            ViewData.Model = data.ToList();

            ViewBag.shopId = id;
            return View("p_foodsMenu");
        }
        public JsonResult Ajax_foods(string id)
        {
            foodC itc = new foodC();
            var data = itc.getsByShopId(id.toOId()).OrderByDescending(d => d.lastDatatime);

            ViewData.Model = data.ToList();
            //ViewBag.shopId = id;
            return Json(data.ToList(), JsonRequestBehavior.AllowGet);
        }
        public ActionResult foods(string id)
        {

            if (string.IsNullOrWhiteSpace(id))
            {
                return RedirectToAction("index","home");
            }

            foodC sc = new foodC();
            var s = sc.getById(id);
            if (s==null)
            {
                return Content("你潮了，我没找到");
            }
            var result = Detail(s.shopId.ToString(), "foods");

            ViewBag.fid = s.Id.ToString();

            return result;
        }
        public ActionResult FindFood(string id,string name)
        {

            if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(name))
            {
                return RedirectToAction("index", "home");
            }

            foodC fc = new foodC();
            var s = fc.getByShopAndName(ObjectId.Parse(id), name);
            if (s == null)
            {
                return Content("你潮了，我没找到");
            }
            return RedirectToAction("Foods",new{id=s.Id});
        }
    }
}
